<?php
defined('_JEXEC') or die;

jimport('joomla.application.component.modelform');
jimport('joomla.event.dispatcher');
 
class BaseModelComunas extends JModelForm
{
	
	public function datos_grid(){
	 	
 	$db = &JFactory::getDBO();
    $pagination = false;
	if (isset($_REQUEST["page"])) {
	   $pagination = true;	
	   $page = intval($_REQUEST["page"]);
	   
	}else{
		$page=0;
	}

	if(isset($_REQUEST["perpage"]))
		$perpage = intval($_REQUEST["perpage"]);
	else
		$perpage = 10;
		
		
	// this variables Omnigrid will send only if serverSort option is true
    if(isset($_REQUEST["sorton"])) { $sorton = $_REQUEST["sorton"]; }else{ $sorton = null; }
	if(isset($_REQUEST["sortby"])) { $sortby = $_REQUEST["sortby"]; }else{ $sortby = null; }
	
	$n = ( $page -1 ) * $perpage;
        $limit = "";
	
	if ( $pagination )
		$limit = "LIMIT $n, $perpage";
	
	$sql= "SELECT CONCAT('<input type=checkbox value=',idcomuna,' name=checks ></input>') as sele" .
			",comuna " .
			",ciudad " .
			",departamento " .
			",pais " .
			",CASE WHEN co.idestado=1 then 'ACTIVO' ELSE 'INACTIVO' END as estado".
			",CONCAT('<a href=javascript:void(0); onclick=editar_comunas(',idcomuna,') >Editar</a>') as editar " .
			" FROM #__comunas co join  #__ciudades ciu using(idciudad) join #__departamentos dep on ciu.iddepartamento=dep.iddepartamento" .
			" join #__paises pai using(idpais) ";
			
	if($sorton) $sql.=" ORDER BY $sorton $sortby ";
	
	if($limit) $sql.=" $limit ";
	
	
        $db->setQuery($sql);
        $db->query();
        $total = $db->getNumRows();
        $row = $db->loadObjectList();
	
	$row = array("page"=>$page, "total"=>$total, "data"=>$row);

	echo json_encode($row);
	}
		
	public function eliminar($id){
		
    	$query = $this->_db->getQuery(true);
		$query->delete();
		$query->from($this->_db->quoteName('#__comunas'));
		$query->where($this->_db->quoteName('idcomuna') . ' in (' .$id.')' );
		$this->_db->setQuery($query);
			
		if($this->_db->query()){
			return true;
		}else{
			return false;
		}
	}

	public function obtenerDatos($idciudad=null,$idcomuna=null){
		$query = $this->_db->getQuery(true);
		$query->select('*');
		$query->from($this->_db->quoteName('#__comunas'));
		if($idciudad) $query->where($this->_db->quoteName('idciudad') . ' = ' . (int) $idciudad);
		if($idcomuna) $query->where($this->_db->quoteName('idcomuna') . ' = ' . (int) $idcomuna);
		$this->_db->setQuery($query);
		return  $this->_db->loadObjectList();
	}
	
	public function getData(){
		$this->data=null;
		
		if(JRequest::getVar('idcomuna')!=null){
			
			$query = $this->_db->getQuery(true);
			$query->select('*');
			$query->from('#__comunas as co ');
			$query->join('LEFT', '#__ciudades AS ciu ON ciu.idciudad = co.idciudad');
			$query->join('LEFT', '#__departamentos AS dep ON ciu.iddepartamento = dep.iddepartamento');
			$query->join('LEFT', '#__paises AS pai ON dep.idpais = dep.idpais');
			$query->where('idcomuna' . ' = ' . (int) JRequest::getVar('idcomuna'));
			$this->_db->setQuery((string)$query);
			$this->data = (array) $this->_db->loadAssoc();
						
		}

		
		if ($this->data === null) {

			$this->data	= new stdClass();
			$app	= JFactory::getApplication();
			$params	= JComponentHelper::getParams('com_base');

			// Override the base user data with any data in the session.
			$temp = (array)$app->getUserState('com_base.comunas.data', array());
			foreach ($temp as $k => $v) {
				$this->data->$k = $v;
			}

			// Get the dispatcher and load the users plugins.
			$dispatcher	= JDispatcher::getInstance();
			JPluginHelper::importPlugin('user');

			// Trigger the data preparation event.
			$results = $dispatcher->trigger('onContentPrepareData', array('com_base.comunas', $this->data));

			// Check for errors encountered while preparing the data.
			if (count($results) && in_array(false, $results, true)) {
				$this->setError($dispatcher->getError());
				$this->data = false;
			}
		}
		
		if(isset($this->data)) return $this->data;
	}

	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_base.Comunas', 'Comunas', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		return $form;
	}

	protected function loadFormData()
	{
		return $this->getData();
	}
	
	protected function populateState()
	{
		// Get the application object.
		$app	= JFactory::getApplication();
		$params	= $app->getParams('com_base');

		// Load the parameters.
		$this->setState('params', $params);
	}

 	function guardar($temp){
 		
   		$row =& JTable::getInstance('comunas','Table');
   			
   		// Merge in the registration data.
		foreach ($temp as $k => $v) {
			$data[$k] = $v;
		}
			
    	// Bind the form fields to the hello table
    	if (!$row->bind($data)) {
	        $this->setError($this->_db->getErrorMsg());
        	return false;
    	}
 
	    // Make sure the hello record is valid
	    if (!$row->check()) {
        	$this->setError($this->_db->getErrorMsg());
        	return false;
    	}
 
	    // Store the web link table to the database
	    if (!$row->store()) {
    	    $this->setError($this->_db->getErrorMsg());
        	return false;
    	}
    	return true;
	}

}
